﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Roton.Engine
{
    /// <summary>
    /// Base class for keyboard buffers.
    /// </summary>
    abstract public class KeyBuffer : IKeyboard
    {
        Queue<KeyEventArgs> buffer = new Queue<KeyEventArgs>();
        KeyEventArgs pressed = null;

        /// <summary>
        /// Clear the KeyBuffer.
        /// </summary>
        public void ClearKeyboard()
        {
            buffer.Clear();
            pressed = null;
        }

        /// <summary>
        /// Get the currently pressed key at the front of the buffer.
        /// </summary>
        public Keys GetPressedKey()
        {
            if (pressed != null)
                return pressed.KeyCode;
            return Keys.None;
        }

        /// <summary>
        /// Returns true if the key code exists in the buffer already.
        /// </summary>
        protected bool IsQueued(KeyEventArgs key)
        {
            return buffer
                .Where(j => j.KeyCode == key.KeyCode)
                .FirstOrDefault() != null;
        }

        /// <summary>
        /// Update the key buffer.
        /// </summary>
        public void PollKeyboard()
        {
            if (buffer.Count > 0)
                pressed = buffer.Dequeue();
            else
                pressed = new KeyEventArgs(Keys.None);
        }

        /// <summary>
        /// Enqueue a key event.
        /// </summary>
        abstract public void Press(KeyEventArgs e);

        /// <summary>
        /// Add a key to the key buffer.
        /// </summary>
        protected void Queue(KeyEventArgs key)
        {
            buffer.Enqueue(key);
        }
    }
}
